//
//  ZXStarAppraiseView.m
//  ZXStarAppraiseViewDemo
//
//  Created by LIUKUN-PC on 16/5/12.
//  Copyright © 2016年 liukun. All rights reserved.
//

#import "ZXStarAppraiseView.h"

#define kViewWidth self.frame.size.width
#define kViewHeight self.frame.size.height

const CGFloat ZXStarAppraiseViewSuggestWidth = 175.0;
const CGFloat ZXStarAppraiseViewSuggestHeight = 40.0;

@interface ZXStarAppraiseView ()

@property (nonatomic, copy) void(^starAppraiseDidCompleteHandler)(NSInteger score);

@property (nonatomic, strong) NSArray<UIImageView *> *starImageViews;
/**
 *  评分结果 0 - 5
 */
@property (nonatomic, assign) NSInteger score;

@end

@implementation ZXStarAppraiseView

#pragma mark - API

- (void)starAppraiseDidComplete:(void (^)(NSInteger))handlerBlock {
    self.starAppraiseDidCompleteHandler = handlerBlock;
}

#pragma mark - OverWrite Init Methods

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        [self initSubViews];
    }
    return self;
}

- (instancetype)initWithCoder:(NSCoder *)coder {
    if (self = [super initWithCoder:coder]) {
        [self initSubViews];
    }
    return self;
}

- (instancetype)init {
    if (self = [super init]) {
        [self initSubViews];
    }
    return self;
}

- (void)layoutSubviews {
    [super layoutSubviews];
    
    CGFloat width = MIN(kViewWidth / 5, kViewHeight);
    
    for (NSInteger i = 0; i < 5; i++) {
        self.starImageViews[i].frame = CGRectMake(2.5 + i * width, (kViewHeight - width + 5) / 2, width - 5, width - 5);
    }

}


#pragma mark - initSubViews

- (void)initSubViews {
    
    [self.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    
    UITapGestureRecognizer *tapGR = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
    [self addGestureRecognizer:tapGR];

    NSMutableArray *starImageViewsMutableArray = [NSMutableArray array];
    for (NSInteger i = 0; i < 5; i++) {
        UIImageView *imageView = [[UIImageView alloc] init];
        
        [starImageViewsMutableArray addObject:imageView];
        [self addSubview:imageView];

    }
    self.starImageViews = [starImageViewsMutableArray copy];
    self.score = 0;
    
}

#pragma mark - Getter & Setter

- (void)setScore:(NSInteger)score {
    _score = score;
    for (NSInteger i = 0; i < 5; i++) {
        if (score - 1 < i) {
            self.starImageViews[i].image = [UIImage imageNamed:@"star_empty_new"];
        } else {
            self.starImageViews[i].image = [UIImage imageNamed:@"star_full_new"];
        }
        
    }
}

#pragma mark - Action

- (void)tapAction:(UITapGestureRecognizer *)tapGR {
    //触摸的地方的index
    CGPoint touchPoint = [tapGR locationInView:self];
    NSInteger touchIndex = touchPoint.x / (kViewWidth / 5);
    self.score = touchIndex + 1;
    if (self.starAppraiseDidCompleteHandler) {
        self.starAppraiseDidCompleteHandler(self.score);
    }
}


@end
